package goodmemo.server.resources;

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.GET;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;

import goodmemo.server.MemoEntry;

import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletContext;

import java.util.List;
import java.util.Calendar;

import goodmemo.server.Config;

@Path("uploadmemo")
public class UploadMemoResources {
    @Context ServletContext context;

    private static Logger log = Logger.getLogger(UploadMemoResources.class);

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello(){
        return "hello";
    }

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public Response uploadMemo(MemoEntry memoEntry) {

        log.debug("[uploadMemo] incoming memoEntry: "+
                    memoEntry);


        Connection conn = null;
        Statement stmt = null;
        PreparedStatement pstmt = null;
        ResultSet r = null;

        try{

            Config conf = Config.getInstance(context);

            DataSource dataSource = conf.getDataSource();

            conn = dataSource.getConnection();

            stmt = conn.createStatement(
                    java.sql.ResultSet.TYPE_FORWARD_ONLY,
                    java.sql.ResultSet.CONCUR_UPDATABLE);


            long memoId = memoEntry.getMemoId();
            long sender = memoEntry.getSender();
            List<Long> receivers = memoEntry.getReceivers();
            String memo = memoEntry.getMemo();
            Calendar c = Calendar.getInstance();
            long mtime =c.getTime().getTime() ;
            stmt.executeUpdate(String.format( 
                "INSERT INTO memos (memoid,sender,memo,mtime)"+
                "values (%d,%d,'%s',%d)",
                memoId,sender,memo,mtime),
                Statement.RETURN_GENERATED_KEYS );

            r = stmt.getGeneratedKeys();

            if (r.next()){
                long memo_id = r.getLong(1);

                pstmt = conn.prepareStatement(
                "INSERT INTO receivers (receiver,memo_id)"+
                "values (?,?)");

                for (long receiver : receivers) {
                    pstmt.setLong(1,receiver);
                    pstmt.setLong(2,memo_id);

                    pstmt.execute();
                }
            }
            else {
                return Response.status(300).build();
            }

        }catch(Exception e){
            log.error("db error",e);
            return Response.status(300).build();
        }
        finally{
            if (conn != null) {
                try{conn.close();}catch(Throwable e){}
            } 
        }
        return Response.ok().build();
    }
}
